package com.hframe.database;


import com.hframe.data.DRef;
import com.hframe.database.plugin.DatabaseMySql;
import com.hframe.type.TInt;
import com.hframe.type.TString;
import org.apache.log4j.Logger;

import java.lang.reflect.Constructor;


public class DatabaseConfig extends DRef<DatabaseConfig> {
    private static Logger log = Logger.getLogger(DatabaseConfig.class);

    private TString url = new TString("jdbc:mysql://localhost:3306/");
    private TString userName = new TString("root");
    private TString userPass = new TString("root");
    private TString tableName = new TString("test");
    private TString param = new TString("?useUnicode=true&characterEncoding=UTF-8&useSSL=false");
    private TString driverName = new TString("com.hframe.database.plugin.DatabaseMySql");
    private Class<? extends Database> driver = DatabaseMySql.class;
    private TInt threadCount = new TInt(0);


    public TString Url() {
        return url;
    }

    public TString UserName() {
        return userName;
    }

    public TString UserPass() {
        return userPass;
    }

    public TString TableName() {
        return tableName;
    }

    public TString Param() {
        return param;
    }

    public TString DriverName() {
        return driverName;
    }

    public Class<? extends Database> getDriver() {
        return driver;
    }

    public void setDriver(Class<? extends Database> driver) {
        this.driver = driver;
    }

    public Database get() {
        if (!threadCount.isEmpty() && threadCount.get() > 0) {
            return DatabasePool.get().getDatabase(this);
        }
        return getDatabase();
    }

    @SuppressWarnings("unchecked")
    public Database getDatabase() {
        try {
            if (null == driver && !driverName.isEmpty()) {
                driver = (Class<? extends Database>) Class.forName(driverName.get());
            }

            if (null != driver) {
                Constructor<? extends Database> c = driver.getDeclaredConstructor(DatabaseConfig.class);
                c.setAccessible(true);
                return c.newInstance(this);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public TInt ThreadCount() {
        return threadCount;
    }
}